package xx.shiro.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xx.shiro.common.Result;
import xx.shiro.entity.SysUser;
import xx.shiro.enums.ResultCodeEnum;

@Slf4j
@RestController
public class LoginController {

    @GetMapping("/login")
    public Result login(SysUser user) {
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return Result.fail(ResultCodeEnum.USER_ERROR);
        }
        //用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            return Result.fail(ResultCodeEnum.USER_NOT_EXISTS);
        } catch (AuthenticationException e) {
            log.info(e.toString());
            return Result.fail(ResultCodeEnum.USER_ERROR);
        } catch (AuthorizationException e) {
            return Result.fail(ResultCodeEnum.AUTHORITY_UNAUTHORIZED);
        }
        return Result.success("登录成功");
    }
}
